package com.xuetang9.t9.xinhuaxia.controller;

import com.xuetang9.t9.xinhuaxia.beans.*;
import com.xuetang9.t9.xinhuaxia.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 陈焱
 * @version 1.0
 * @desc
 * @time 2020/2/25 下午 7:19
 * @copyright liyq
 * @address 成都西部国际金融中心2栋2201
 **/
@Controller
@RequestMapping("social")
public class SocialController {

    @Autowired
    private ISocialPublishService socialPublishService;
    @Autowired
    private ISocialPictureService socialPictureService;
    @Autowired
    private ISocialChatService socialChatService;
    @Autowired
    private ISocialCollectionService socialCollectionService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IChatService chatService;
    @RequestMapping(value = "/upload", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String fileupload(HttpServletRequest request, MultipartFile[] files,int userid,String worktitle,String modelname,String photographer,String desc,String dynamicTags ){
        System.out.println("文件上传");
        SocialPublish addSocialPublish =new SocialPublish();
        int MaxCountId;
        if(socialPublishService.getSocialPublishMaxCountId()==0){
            MaxCountId=1;
        }else {
            MaxCountId=(socialPublishService.getSocialPublishMaxCountId())+1;
        }
        addSocialPublish.setpId(MaxCountId);
        addSocialPublish.setpUserid(userid);
        addSocialPublish.setpWorktitle(worktitle);
        addSocialPublish.setpModelname(modelname);
        addSocialPublish.setpPhotographer(photographer);
        addSocialPublish.setpTag(dynamicTags);
        addSocialPublish.setpPhotodescribe(desc);
        addSocialPublish.setpLike(0);
        boolean add = socialPublishService.add(addSocialPublish);
        if(files!=null&&files.length>0){
            for(int i=0;i<files.length;i++){
               MultipartFile file=files[i];
               saveFile(file,request,MaxCountId,userid);
               }
            }
        return "success";
    }

    private boolean saveFile(MultipartFile upload,HttpServletRequest request,int maxcountid,int userid) {
        // 判断文件是否为空
        if (!upload.isEmpty()) {
            try {
                // 文件保存路径
                String filePath = request.getSession().getServletContext().getRealPath("/backstage/upload/");
                File file =new File(filePath);
                if(!file.exists()){
                    file.mkdirs();
                }
                String filename=upload.getOriginalFilename();
                String uuid= UUID.randomUUID().toString().replace("-","");
                filename=uuid+"-"+filename;
                // 转存文件
                upload.transferTo(new File(filePath,filename));
                SocialPicture addSocialPicture=new SocialPicture();
                addSocialPicture.setpId(maxcountid);
                addSocialPicture.setpUserid(userid);
                addSocialPicture.setpPhotopath("/backstage/upload/"+filename);
                socialPictureService.add(addSocialPicture);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @RequestMapping("/queryallpublish")
    private @ResponseBody  List<Publish>  queryAllPublish(){
        List<Publish> publishes=new ArrayList();
        List<SocialPublish> socialPublishes=socialPublishService.queryAll();
        for(int i=0;i<socialPublishes.size();i++){
            Publish publish=new Publish();
            publish.setSocialPublish(socialPublishes.get(i));
            User user = userService.queryById(socialPublishes.get(i).getpUserid().longValue());
            if (null!=user){
                String username = user.getuUsername();
                String getuImgpath = user.getuImgpath();
                publish.setUsername(username);
                publish.setUserheadimg(getuImgpath);
            }
            List<String> picpath=new ArrayList();
            List<SocialPicture> socialPictures=socialPictureService.queyByPublishId(socialPublishes.get(i).getpId());
            int size =socialPictures.size() > 3 ? 3 : socialPictures.size();
            for(int y=0;y<size;y++){
                picpath.add(socialPictures.get(y).getpPhotopath());
            }
            publish.setSociapPicturePath(picpath);
            publish.setSocialChatCountl(socialChatService.getChatCountByPublishId(socialPublishes.get(i).getpId()));
            publish.setSocialCollectionCount(socialCollectionService.getCollectionCountByPublishId(socialPublishes.get(i).getpId()));
            publishes.add(publish);
        }
        return publishes;
    }

    @RequestMapping("/queryallpublishbyid")
    private @ResponseBody  List<Publish>  queryallpublishbyid(Integer userid){
        List<Publish> publishes=new ArrayList();
        List<SocialPublish> socialPublishes=socialPublishService.queryAllByUser(userid);
        socialPublishes.forEach(System.out::println);
        for(int i=0;i<socialPublishes.size();i++){
            Publish publish=new Publish();
            publish.setSocialPublish(socialPublishes.get(i));
            publish.setUsername(userService.queryById(socialPublishes.get(i).getpUserid().longValue()).getuUsername());
            publish.setUserheadimg(userService.queryById(socialPublishes.get(i).getpUserid().longValue()).getuImgpath());
            List<String> picpath=new ArrayList();
            List<SocialPicture> socialPictures=socialPictureService.queyByPublishId(socialPublishes.get(i).getpId());
            int size =socialPictures.size()>3?3:socialPictures.size();
            for(int y=0;y<size;y++){
                picpath.add(socialPictures.get(y).getpPhotopath());
            }
            publish.setSociapPicturePath(picpath);
            publish.setSocialChatCountl(socialChatService.getChatCountByPublishId(socialPublishes.get(i).getpId()));
            publish.setSocialCollectionCount(socialCollectionService.getCollectionCountByPublishId(socialPublishes.get(i).getpId()));
            publishes.add(publish);
        }
        return publishes;
    }

    @RequestMapping("/collectionSocialbyuid")
    private @ResponseBody  List<Publish>  collectionSocialbyuid(Integer userid){
        List<Publish> publishes=new ArrayList();
        SocialCollection socialCollection=new SocialCollection();
        socialCollection.setpCollectuserid(userid);
        List<SocialCollection> socialCollections=socialCollectionService.querySocialCollectionbyuserid(socialCollection);
        List<SocialPublish> socialPublishes=new ArrayList();
        socialCollections.forEach(sc->{
            SocialPublish searchsc=new SocialPublish();
            searchsc.setpId(sc.getpId());
            socialPublishes.add(socialPublishService.querybypid(searchsc));
        });
        for(int i=0;i<socialPublishes.size();i++){
            Publish publish=new Publish();
            publish.setSocialPublish(socialPublishes.get(i));
            publish.setUsername(userService.queryById(socialPublishes.get(i).getpUserid().longValue()).getuUsername());
            publish.setUserheadimg(userService.queryById(socialPublishes.get(i).getpUserid().longValue()).getuImgpath());
            List<String> picpath=new ArrayList();
            List<SocialPicture> socialPictures=socialPictureService.queyByPublishId(socialPublishes.get(i).getpId());
            int size =socialPictures.size()>3?3:socialPictures.size();
            for(int y=0;y<size;y++){
                picpath.add(socialPictures.get(y).getpPhotopath());
            }
            publish.setSociapPicturePath(picpath);
            publish.setSocialChatCountl(socialChatService.getChatCountByPublishId(socialPublishes.get(i).getpId()));
            publish.setSocialCollectionCount(socialCollectionService.getCollectionCountByPublishId(socialPublishes.get(i).getpId()));
            publishes.add(publish);
        }
        return publishes;
    }

    @RequestMapping("/addcollection")
    private @ResponseBody  String addcollection(@RequestBody SocialCollection socialCollection){
        int count=socialCollectionService.getCollectionCountByPiduid(socialCollection);
        if(count>0){
            return "addcollectionfail";
        }else{
           if(socialCollectionService.addCollection(socialCollection)) {
               return "addcollectionsucess";
           }
        }
        return "addcollectionfail";
    }

    @RequestMapping("/deletecollection")
    private @ResponseBody  String deletecollection(Integer pid,Integer uid){
        SocialCollection socialCollection=new SocialCollection();
        socialCollection.setpId(pid);
        socialCollection.setpCollectuserid(uid);
        if(socialCollectionService.remove(socialCollection)){
            return "deletecollectionsucess";
        }
        return "deletecollectionfail";
    }

    @RequestMapping("/addlike")
    private @ResponseBody  String addlike(Integer pid) {
        if(socialPublishService.addlike(pid)){
            return "addlikesucess";
        }
        return "addlikefail";
    }

    @RequestMapping("/queryDetailbypid")
    private @ResponseBody  PublishDetai  queryDetailbypid(Integer pid){
        PublishDetai publishDetai=new PublishDetai();
        SocialPublish socialPublish=new SocialPublish();
        socialPublish.setpId(pid);
        publishDetai.setSocialPublish(socialPublishService.querybypid(socialPublish));
        List<SocialPicture> socialPictures = socialPictureService.queyByPublishId(pid);
        List<String>path=new ArrayList();
        socialPictures.forEach(socialPicture -> {
            path.add(socialPicture.getpPhotopath());
        });
        publishDetai.setSociapPicturePath(path);
        publishDetai.setSocialChats(socialChatService.queryBypid(pid));
        return publishDetai;
    }

    @RequestMapping("/addContent")
    private @ResponseBody  String  addContent(Integer publishid,Integer userid,String Content){
        SocialChat socialChat =new SocialChat();
        socialChat.setpId(publishid);
        socialChat.setpUserid(userid);
        socialChat.setpChatid(null);
        int chatid=1;
        if(socialChatService.add(socialChat)){
            chatid=socialChat.getpChatid();
        };
        Chat chat=new Chat();
        chat.setpChatid(chatid);
        chat.setpContent(Content);
        if(chatService.add(chat)){
            return "addchatsucess";
        };
        return "addchatfail";
    }
}

